
package combat.example.server.protocol.implementation;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

import combat.example.protocol.data.ChatEntry;
import combat.example.protocol.interfaces.ChatInt;


/**
 * 
 * @author Laurens Andriessen
 * @version 1.0
 */
public class Chat implements ChatInt {

	// Since we only want ONE Chat: create ONE instance of the Chat-class
	// http://radio-weblogs.com/0122027/stories/2003/10/20/implementingTheSingletonPatternInJava.html
	protected Chat() {}
	private static Chat _instance = null;
	public final static Chat instance() {
		return (_instance == null) ? new Chat() : _instance;
	}

	// Members
	private static ArrayList<ChatEntry> chats = new ArrayList<ChatEntry>();
	private static String chatHash = "";

	// Methods
	public synchronized ArrayList<ChatEntry> getChats() {
		return (chats == null) ? new ArrayList<ChatEntry>() : chats;
	}
	public synchronized void setChats(ArrayList<ChatEntry> chats) {
		Chat.chats = chats;
	}

	public synchronized String getChatHash() {
		return chatHash;
	}
	public synchronized void setChatHash(String chatHash) {
		Chat.chatHash = chatHash;
	}
	public void generateChatHash() {
		MessageDigest digest = null;
		try {
			digest = java.security.MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			System.out.println("Error! MD5 MessageDigest instance could not be found.");
			e.printStackTrace();
			System.exit(0);
		}
		byte[] bytes = chats.toString().getBytes();
		digest.update(bytes);
		chatHash = digest.digest().toString();
	}

	public synchronized void sendChat(int clientID, int targetID, String message) {
		chats.add(new ChatEntry(clientID, targetID, message));
		generateChatHash();
	}
}
